package com.campus.counseling.controller;

import com.campus.counseling.model.common.Result;
import com.campus.counseling.model.vo.LoginStatsVO;
import com.campus.counseling.model.vo.TimeDistributionVO;
import com.campus.counseling.model.vo.UserActiveVO;
import com.campus.counseling.service.LoginAnalysisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Tag(name = "登录分析")
@RestController
@RequestMapping("/api/analysis/login")
@RequiredArgsConstructor
public class LoginAnalysisController {

    private final LoginAnalysisService loginAnalysisService;

    @GetMapping("/stats")
    @Operation(summary = "获取登录统计数据")
    public Result<LoginStatsVO> getLoginStats(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        // 如果没有提供日期，默认查询最近7天的数据
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(6); // 最近7天（包括今天）
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }
        return Result.success(loginAnalysisService.getLoginStats(startDate, endDate));
    }

    @GetMapping("/active-users")
    @Operation(summary = "获取活跃用户数据")
    public Result<List<UserActiveVO>> getActiveUsers(
            @RequestParam(defaultValue = "day") String timeRange) {
        return Result.success(loginAnalysisService.getActiveUsers(timeRange));
    }

    @GetMapping("/time-distribution")
    @Operation(summary = "获取登录时间分布")
    public Result<List<TimeDistributionVO>> getLoginTimeDistribution(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        // 如果没有提供日期，默认使用今天
        if (date == null) {
            date = LocalDate.now();
        }
        return Result.success(loginAnalysisService.getLoginTimeDistribution(date));
    }

    @GetMapping("/geo-distribution")
    @Operation(summary = "获取登录地理分布")
    public Result<List<Map<String, Object>>> getLoginGeoDistribution() {
        return Result.success(loginAnalysisService.getLoginGeoDistribution());
    }

    @GetMapping("/device-distribution")
    @Operation(summary = "获取设备分布")
    public Result<List<Map<String, Object>>> getDeviceDistribution() {
        return Result.success(loginAnalysisService.getDeviceDistribution());
    }
} 